﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using VSDBM.Code.dao;
using VSDBM.Code.dto;
using VSDBM.Code.functions;
using System.IO;


public partial class Visual_CRUD_Group_AddGroup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillOrganism();
            FillOrganismFilter();
        }
    }
    protected void FillOrganismFilter()
    {
        DataSet ds = OrganismDAO.select("WHERE status=1", "ORDER BY name");
        //verifica erro na querry
        if (ds.Tables.Count == 0)
        {
            Exception ex = new Exception("Table not found!");
            throw ex;
        }
        //verifica se existem organismos cadastrados.
        else if (ds.Tables[0].Rows.Count == 0)
        {
            DataRow dr = ds.Tables[0].NewRow();
            ds.Tables[0].Rows.InsertAt(dr, 0);
            ds.Tables[0].Rows[0]["name"] = "NO ORGANISMS FOUND";
            ds.Tables[0].Rows[0]["id"] = "0";

        }
        //Insere os organismos no Dropdown List(ddOrganismFilter).

        ddOrganismFilter.DataSource = ds.Tables[0];
        ddOrganismFilter.DataTextField = "name";
        ddOrganismFilter.DataValueField = "id";
        ddOrganismFilter.DataBind();

    }
    protected void FillSubtype(String idorganism)
    {
        
        DataSet ds = SubtypeDAO.select("WHERE status=1 AND idorganisms="+ idorganism, "ORDER BY description");
        //verifica erro na querry
        if (ds.Tables.Count == 0)
        {
            Exception ex = new Exception("Table not found!");
            throw ex;
        }
        //verifica se existem organismos cadastrados.
        else if (ds.Tables[0].Rows.Count == 0)
        {
            DataRow dr = ds.Tables[0].NewRow();
            ds.Tables[0].Rows.InsertAt(dr, 0);
            ds.Tables[0].Rows[0]["description"] = "NO SUBTYPES FOUND";
            ds.Tables[0].Rows[0]["id"] = "0";

        }
        //Insere os organismos no Dropdown List(ddSubtypes).

        ddSubtype.DataSource = ds.Tables[0];
        ddSubtype.DataTextField = "description";
        ddSubtype.DataValueField = "id";
        ddSubtype.DataBind();

    }
    protected void FillOrganism()
    {
        DataSet ds = OrganismDAO.select("WHERE status=1", "ORDER BY name");
        //verifica erro na querry
        if (ds.Tables.Count == 0)
        {
            Exception ex = new Exception("Table not found!");
            throw ex;
        }
        //verifica se existem organismos cadastrados.
        else if (ds.Tables[0].Rows.Count == 0)
        {
            DataRow dr = ds.Tables[0].NewRow();
            ds.Tables[0].Rows.InsertAt(dr, 0);
            ds.Tables[0].Rows[0]["name"] = "NO ORGANISMS FOUND";
            ds.Tables[0].Rows[0]["id"] = "0";

        }
        //Insere os organismos no Dropdown List(ddOrganism).

        ddOrganism.DataSource = ds.Tables[0];
        ddOrganism.DataTextField = "name";
        ddOrganism.DataValueField = "id";
        ddOrganism.DataBind();

    }
    protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        
    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (RadioButtonList1.SelectedIndex == 0)
        {
            //organism
            lblOrganism.Visible = true;
            ddOrganism.Visible = true;
            btnCreateOrganism.Visible = true;
            lblOrganismFilter.Visible = false;
            lblSubtype.Visible = false;
            ddOrganismFilter.Visible = false;
            ddSubtype.Visible = false;
            btnCreateSubtype.Visible = false;
            lblFile.Visible = false;
            FileUpload1.Visible = false;
            btnCreateFile.Visible = false;
        }
        else if (RadioButtonList1.SelectedIndex == 1)
        {
            //subtype
            lblOrganism.Visible = false;
            ddOrganism.Visible = false;
            btnCreateOrganism.Visible = false;
            lblOrganismFilter.Visible = true;
            lblSubtype.Visible = true;
            ddOrganismFilter.Visible = true;
            ddSubtype.Visible = true;
            btnCreateSubtype.Visible = true;
            lblFile.Visible = false;
            FileUpload1.Visible = false;
            btnCreateFile.Visible = false;
        }
        else if (RadioButtonList1.SelectedIndex == 2)
        {
            //acession file
            lblOrganism.Visible = false;
            ddOrganism.Visible = false;
            btnCreateOrganism.Visible = false;
            lblOrganismFilter.Visible = false;
            lblSubtype.Visible = false;
            ddOrganismFilter.Visible = false;
            ddSubtype.Visible = false;
            btnCreateSubtype.Visible = false;
            lblFile.Visible = true;
            FileUpload1.Visible = true;
            btnCreateFile.Visible = true;
        }
    }
    protected void btnCreateOrganism_Click(object sender, EventArgs e)
    {
        //Create gruop by Organism
        VSDBM.Code.dto.User usuariologado = (VSDBM.Code.dto.User)HttpContext.Current.Session["usuariologado"];
        int Userid = usuariologado.id;
        String OrganismId = ddOrganism.SelectedValue;
        List<Sequence> SequenceList = SequenceDAO.DStoList(SequenceDAO.select("WHERE idorganism="+OrganismId,""));
        if (SequenceList.Count == 0)
        {
            HttpContext.Current.Session["exception"] = "NO SEQUENCES ADDED FOR THIS ORGANISM";
            Response.Redirect("../../../Visual/Errors/error.aspx");
        }
        else
        {
            if (txtGroupDescription.Text == "")
            {
                HttpContext.Current.Session["exception"] = "PLEASE ADD AN GROUP DESCRIPTION TO PROCEED";
                Response.Redirect("../../../Visual/Errors/error.aspx");
            }
               
            String retorno = GroupsDAO.add(new Groups(0, txtGroupDescription.Text, Userid, 1));
            if (retorno == "Group with this description already exist.")
            {
                HttpContext.Current.Session["exception"] = "Group with this description already exist.";
                Response.Redirect("../../../Visual/Errors/error.aspx");
            }
            else
            {
                DataSet ds = GroupsDAO.select("WHERE description='" + txtGroupDescription.Text+"'", "");
                int groupid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                foreach (Sequence Seq in SequenceList)
                {
                    GroupsDAO.addSequence(groupid, Seq.id);
                }
                Response.Redirect("../../../Visual/CRUD/Group/ListGroup.aspx");
               // HttpContext.Current.Session["done"] = "The group was created with " + SequenceList.Count + " Sequences.";
               // Response.Redirect("../../../Visual/Done/Done.aspx");
            }
            
        }
        

    }
    protected void btnCreateSubtype_Click(object sender, EventArgs e)
    {
        //Create Gruop by Subtype
        VSDBM.Code.dto.User usuariologado = (VSDBM.Code.dto.User)HttpContext.Current.Session["usuariologado"];
        int Userid = usuariologado.id;
        String SubtypeId = ddSubtype.SelectedValue;
        List<Sequence> SequenceList = new List<Sequence>();
        List<Sequence_Subtype> seq_subList = Sequence_SubtypeDAO.DStoList(Sequence_SubtypeDAO.select("WHERE idsubtype=" + Convert.ToInt32(SubtypeId), ""));
        if (seq_subList.Count <= 0)
        {
            HttpContext.Current.Session["exception"] = "NO SEQUENCES ADDED FOR THIS SUBTYPE";
            Response.Redirect("../../../Visual/Errors/error.aspx");
        }
        else
        {
            foreach(Sequence_Subtype seq_sub in seq_subList)
            {
                List<Sequence> TempList = SequenceDAO.DStoList(SequenceDAO.select("WHERE id=" + seq_sub.idsequence, ""));
                SequenceList.Add(TempList[0]);
            }
            if (txtGroupDescription.Text == "")
            {
                HttpContext.Current.Session["exception"] = "PLEASE ADD AN GROUP DESCRIPTION TO PROCEED";
                Response.Redirect("../../../Visual/Errors/error.aspx");
            }

            String retorno = GroupsDAO.add(new Groups(0, txtGroupDescription.Text, Userid, 1));
            if (retorno == "Group with this description already exist.")
            {
                HttpContext.Current.Session["exception"] = "Group with this description already exist.";
                Response.Redirect("../../../Visual/Errors/error.aspx");
            }
            else
            {
                DataSet ds = GroupsDAO.select("WHERE description='" + txtGroupDescription.Text + "'", "");
                int groupid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                foreach (Sequence Seq in SequenceList)
                {
                    GroupsDAO.addSequence(groupid, Seq.id);
                }
                Response.Redirect("../../../Visual/CRUD/Group/ListGroup.aspx");
            }

        }
        
    }
    protected void btnCreateFile_Click(object sender, EventArgs e)
    {
        //Create Group by Acession File
        List<String> IdList = getFileContent();
        VSDBM.Code.dto.User usuariologado = (VSDBM.Code.dto.User)HttpContext.Current.Session["usuariologado"];
        int Userid = usuariologado.id;
        List<Sequence> SequenceList = new List<Sequence>();
        
        
            foreach (String acession in IdList)
            {
                List<Sequence> TempList = SequenceDAO.DStoList(SequenceDAO.select("WHERE idacession='" + acession+"'", ""));
                if (TempList.Count > 0)
                {
                    SequenceList.Add(TempList[0]);
                }
            }
            if (txtGroupDescription.Text == "")
            {
                HttpContext.Current.Session["exception"] = "PLEASE ADD AN GROUP DESCRIPTION TO PROCEED";
                Response.Redirect("../../../Visual/Errors/error.aspx");
            }

            String retorno = GroupsDAO.add(new Groups(0, txtGroupDescription.Text, Userid, 1));
            if (retorno == "Group with this description already exist.")
            {
                HttpContext.Current.Session["exception"] = "Group with this description already exist.";
                Response.Redirect("../../../Visual/Errors/error.aspx");
            }
            else
            {
                DataSet ds = GroupsDAO.select("WHERE description='" + txtGroupDescription.Text + "'", "");
                int groupid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                foreach (Sequence Seq in SequenceList)
                {
                    GroupsDAO.addSequence(groupid, Seq.id);
                }
                Response.Redirect("../../../Visual/CRUD/Group/ListGroup.aspx");
            }

        





    }

    protected List<String> getFileContent()
    {
        List<String> Lista = new List<string>();
        if (FileUpload1.HasFile)
        {
            
                try
                {

                    //Obtém o conteúdo do arquivo e passa para o DataSet.
                    Stream file = FileUpload1.FileContent;
                    StreamReader reader = new StreamReader(file);
                    String content = reader.ReadToEnd();
                    Lista = new List<String>(content.Split(',').ToList());
                    if (Lista.Count <= 0)
                    {
                        HttpContext.Current.Session["exception"] = "NO ID`s FOUND. PLS UPLOAD ANOTHER FILE.";
                        Response.Redirect("../../../Visual/Errors/error.aspx");
                    }
                    else
                    {
                        return Lista;
                    }

                }
                catch (Exception ex)
                {
                    HttpContext.Current.Session["exception"] = ex.Message;
                    Response.Redirect("../../../Visual/Errors/error.aspx");
                    return Lista;
                }

            
            
                HttpContext.Current.Session["exception"] = "The selected file is not an valid 'text' file. ";
                Response.Redirect("../../../Visual/Errors/error.aspx");
                return Lista;
           
        }
        else
        {
            HttpContext.Current.Session["exception"] = "ERROR: You Should select a file to upload";
            Response.Redirect("../../../Visual/Errors/error.aspx");
            return Lista;

        }
        return Lista;
    }
    protected void ddOrganismFilter_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillSubtype(ddOrganismFilter.SelectedValue);
    }
}